package icu.sunway.gushenBlogBackEnd.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    private static final long time = 1000 * 3600 * 24;
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);


    public static String generateToken(String userId) {
        JwtBuilder jwtBuilder = Jwts.builder();
        return jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .claim("userId", userId)
                .claim("date", new Date())
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .setId(UUID.randomUUID().toString())
                .setSubject("user-check")
                .compact();
    }

    public static String parseTokenAsId(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
        try {
            if (claims.getExpiration().before(new Date())) {
                return null;
            }
            return claims.get("userId", String.class);
        } catch (Exception e) {
            return null;
        }
    }

}
